package dxn.nl.export.deal.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class EasyExcelLocalDateTimeConverter implements Converter<LocalDateTime> {

    private DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    public EasyExcelLocalDateTimeConverter() {
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException {
        String data = cellData.getStringValue();
        if(StringUtils.isBlank(data))
        {
            return null;
        }

        if(data.contains("-"))
        {
            return LocalDateTime.parse(data,dateTimeFormatter1);
        }
        return LocalDateTime.parse(data,dateTimeFormatter2);
    }

    public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {

        if(value == null)
        {
            return new WriteCellData();
        }
        return new WriteCellData(dateTimeFormatter1.format(value));
    }
}


